package com.denny.devdemo.sectionlist;

import android.content.Context;
import android.graphics.Canvas;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

public class SectionListView extends ListView {

	private View mPinnedHeaderView;
	private int mPinnedHeaderWidth;
	private int mPinnedHeaderHeight;
	private SectionListAdapter mAdapter;
	private boolean mHeadViewVisiable;

	public SectionListView(Context context) {
		super(context);
	}

	public void setPinnedHeaderView(View v) {
		this.mPinnedHeaderView = v;
		if (mPinnedHeaderView != null) {
			setFadingEdgeLength(0);
		}

		requestLayout();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		if (mPinnedHeaderView != null) {
			measureChild(mPinnedHeaderView, widthMeasureSpec, heightMeasureSpec);
			mPinnedHeaderWidth = mPinnedHeaderView.getMeasuredWidth();
			mPinnedHeaderHeight = mPinnedHeaderView.getMeasuredHeight();
		}
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
		if (mPinnedHeaderView != null) {
			mPinnedHeaderView.layout(0, 0, mPinnedHeaderWidth,mPinnedHeaderHeight);
			configPinnedHeadView(getFirstVisiblePosition());
		}
	}

	public void configPinnedHeadView(int position) {
		if (mPinnedHeaderView == null) {
			return;
		}
		int state = mAdapter.getPinnedHeadViewState(position);
		switch (state) {
		case SectionListAdapter.PINNED_HEAD_VIEW_GONE:

			mHeadViewVisiable = false;
			break;

		case SectionListAdapter.PINNED_HEAD_VIEW_VISIABLE:
			if (mPinnedHeaderView != null) {
				mAdapter.initPinnedHeadView(mPinnedHeaderView, position);
				mPinnedHeaderView.layout(0, 0, mPinnedHeaderWidth,
						mPinnedHeaderHeight);
			}
			mHeadViewVisiable = true;
			break;
		case SectionListAdapter.PINNED_HEAD_VIEW_UP:
			View firstView = getChildAt(0);
			int y = 0;
			int bottom = firstView.getBottom();
			int height = mPinnedHeaderView.getHeight();
			if (firstView != null) {
				if (bottom < height) {
					y = bottom - height;
				} else {
					y = 0;
				}
				mAdapter.initPinnedHeadView(mPinnedHeaderView, position);
				mPinnedHeaderView.layout(0, y, mPinnedHeaderWidth,
						mPinnedHeaderHeight + y);
			}
			mHeadViewVisiable = true;
			break;
		default:
			break;
		}
	}

	@Override
	protected void dispatchDraw(Canvas canvas) {
		super.dispatchDraw(canvas);
		if (mHeadViewVisiable) {
			drawChild(canvas, mPinnedHeaderView, getDrawingTime());
		}
	}

	@Override
	public void setAdapter(ListAdapter adapter) {
		super.setAdapter(adapter);
		this.mAdapter = (SectionListAdapter) adapter;
	}
}
